

if (not commonlib.USE_LUV) then return {} end 

local __luv__ = require("luv");
commonlib.__luv__ = __luv__;

local Socket = commonlib.inherit(commonlib.ToolBase);
Socket:Property("Server");

function Socket:ctor()

end

function Socket:Init(server)
    self:SetServer(server);
    return self;
end

function Socket:IsValid()
    return self.__luv_tcp__ ~= nil;
end

function Socket:Send(data)
    self.__luv_tcp__:write(data, commonlib.bind(self.OnSend, self));
end

function Socket:OnSend()
end

function Socket:OnConnection()
end

function Socket:OnRecv(data)
    local server = self:GetServer();
    if (not server) then return end 
    server:Handle(self, data);
end

function Socket:OnDisconnection()
end

function Socket:Close()
    if (self.__luv_tcp__) then
        self.__luv_tcp__:shutdown();
        self.__luv_tcp__:close();
        self.__luv_tcp__ = nil;
    end
    self:OnDisconnection();
end

local Server = commonlib.inherit(commonlib.ToolBase);

function Server:ctor()
end

function Server:Init()
    return self;
end

function Server:NewSocket()
    return Socket:new():Init(self);
end

function Server:Start(ip, port)
    ip = ip or "0.0.0.0";
    port = port or 80;
    self.__luv_tcp__ = __luv__.new_tcp();
    self.__luv_tcp__:bind(ip, port);
    commonlib.info("Server Start:", ip, port);
    self.__luv_tcp__:listen(128, function (err)
        if (err) then
            commonlib.error("Server Connect ERROR:", err);
            return ;
        end

        local socket = self:NewSocket();
        socket.__luv_tcp__ = __luv__.new_tcp();
        self.__luv_tcp__:accept(socket.__luv_tcp__);
        socket:OnConnection();
        socket.__luv_tcp__:read_start(function (err, data)
            if (err) then
                print("LUV ERROR:", err);
                return ;
            elseif(data) then
                socket:OnRecv(data);
            else
                socket:Close();
            end
        end)
    end)
end

function Server:Stop()
    if (self.__luv_tcp__) then
        self.__luv_tcp__:close();
        self.__luv__ = nil;
    end
end

commonlib.Server = Server;
commonlib.Socket = Socket;

commonlib.SetInterval(nil, function()
    __luv__.run();
end);

return {};